//
//  ST_BTPrivacyViewController.swift
//  btvideo
//
//  Created by mac on 2020/7/14.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import NIMSDK
#if !targetEnvironment(simulator)
import Contacts
#endif


class ST_BTPrivacyViewController: ST_BTLightBarViewController {
    
    init(accountAdditionalAttributes:ST_BTAccountAdditionalAttribute) {
        self.attributes = accountAdditionalAttributes
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    let attributes:ST_BTAccountAdditionalAttribute
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title_nav_btn.setTitleForAllStates("隐私")
        
         
        
        self.view.addSubview(scrollView)
        scrollView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: statusBarHeight+49, left: 0, bottom: 0, right: 0))
        }
        
        
        scrollView.addSubview(root_view)
        root_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
            make.width.equalToSuperview()
//            make.height.equalToSuperview().offset(10)
            if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .female{
                make.height.equalTo(ScreenHeight+160)
            }else{
                make.height.equalTo(ScreenHeight+20)
            }
        }
        
        root_view.addSubview(item0)
        root_view.addSubview(item1)
        root_view.addSubview(item2)
        root_view.addSubview(item3)
        root_view.addSubview(item4)
        
        root_view.addSubview(item6)
        
        var lastTempItem:UIView = item6
        
        if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .female{
            root_view.addSubview(item7)
            root_view.addSubview(item8)
            root_view.addSubview(item9)
            lastTempItem = item9
        }
        
        
        
        item0.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(80)
            make.top.equalToSuperview().offset(5)
        }
        
        item1.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(80)
            make.top.equalTo(item0.snp.bottom)
        }
        
        
        item2.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(80)
            make.top.equalTo(item1.snp.bottom)
        }
        
        item3.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(80)
            make.top.equalTo(item2.snp.bottom)
        }
        
        if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .female{
            item7.snp.makeConstraints { (make) in
                make.left.right.equalToSuperview()
                make.height.equalTo(80)
                make.top.equalTo(item3.snp.bottom)
            }
            
            item8.snp.makeConstraints { (make) in
                make.left.right.equalToSuperview()
                make.height.equalTo(80)
                make.top.equalTo(item7.snp.bottom)
            }
            item9.snp.makeConstraints { (make) in
                make.left.right.equalToSuperview()
                make.height.equalTo(80)
                make.top.equalTo(item8.snp.bottom)
            }
        }
        
        
        item4.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(60)
            if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .female{
                make.top.equalTo(lastTempItem.snp.bottom)
            }else{
                make.top.equalTo(item3.snp.bottom)
            }
        }
        
        
        item6.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(60)
            make.top.equalTo(item4.snp.bottom)
        }
        
        
//        简单改下待优化
//        if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .female{
//            root_view.addSubview(item10)
//            item10.snp.makeConstraints { (make) in
//                make.left.right.equalToSuperview()
//                make.height.equalTo(item2)
//                make.top.equalTo(item6.snp.bottom)
//            }
//
//        }else if let last = root_view.subviews.last{
//
//            root_view.addSubview(item10)
//            item10.snp.makeConstraints { (make) in
//                make.left.right.equalToSuperview()
//                make.height.equalTo(item2)
//                make.top.equalTo(last.snp.bottom)
//            }
//
//
//        }
        
    }
    
    
    
    
    //    MARK: - Properties
    fileprivate lazy var scrollView:UIScrollView = {
        let control = UIScrollView()
        control.backgroundColor = .white
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.showsVerticalScrollIndicator = false
        return control
    }()
    
    fileprivate lazy var root_view:UIView = {
        let control = UIView()
        return control
    }()
    
    fileprivate lazy var item0:PrivacySupplementBoxView = {
        let control = PrivacySupplementBoxView()
        control.model = PrivacySupplementBoxViewModel.init(title: "屏蔽手机联系人", content: "开启后，手机联系人将不会发现你", isOn: attributes.ignoreMyContacts)
        control.tapSwitchclosure = {[weak self] isOn in
            self?.tapContactHandle(isOn: isOn)
        }
        return control
    }()
    
    fileprivate lazy var item1:PrivacySupplementBoxView = {
        let control = PrivacySupplementBoxView()
        control.model = PrivacySupplementBoxViewModel.init(title: "只允许认证通过用户与我对话", content: "开启后，未认证用户将不能给你发送消息", isOn: attributes.allowTalkFaceDetected)
        control.tapSwitchclosure = {[weak self] isOn in
            
            self?.tapOnlyFaceHandle(isOn: isOn)
        }
        return control
    }()
    
    fileprivate lazy var item2:PrivacySupplementBoxView = {
        let control = PrivacySupplementBoxView()
        control.model = PrivacySupplementBoxViewModel.init(title: "只允许伴心会员用户与我对话", content: "开启后，非会员用户将不能给你发送消息", isOn: attributes.allowMember)
        control.tapSwitchclosure = {[weak self] isOn in
            self?.tapOnlyMemberHandle(isOn: isOn)
        }
        return control
    }()
    
    fileprivate lazy var item3:PrivacySupplementBoxView = {
        let control = PrivacySupplementBoxView()
        control.model = PrivacySupplementBoxViewModel.init(title: "聊天不接收图片和视频", content: "开启后，将不会收到图片和视频消息", isOn: attributes.onlyAllowTextTalk)
        control.tapSwitchclosure = {[weak self] isOn in
            self?.tapOnlyTextTalkHandle(isOn: isOn)
        }
        return control
    }()
    
    fileprivate lazy var item7:PrivacySupplementBoxView = {
        let control = PrivacySupplementBoxView()
        control.model = PrivacySupplementBoxViewModel.init(title: "允许系统打招呼", content: "开启后，系统可能偶尔帮你打招呼", isOn: attributes.allowAutoSayHi)
        control.checkFaceStatus = false
        control.tapSwitchclosure = {[weak self] isOn in
            self?.tapAllowAutoSayHiHandle(isOn: isOn)
        }
        return control
    }()
    
    fileprivate lazy var item9:PrivacySupplementBoxView = {
        let control = PrivacySupplementBoxView()
        control.model = PrivacySupplementBoxViewModel.init(title: "隐藏自己的贵族", content: "开启后，你的贵族勋章和气泡不会显示", isOn: attributes.myNobilityHid)
        control.checkFaceStatus = false
        control.tapSwitchclosure = {[weak self] isOn in
            self?.tapHiddenNobleHandle(isOn: isOn)
        }
        return control
    }()
    
    
    fileprivate lazy var item8:PrivacySupplementBoxView = {
        let control = PrivacySupplementBoxView()
        control.model = PrivacySupplementBoxViewModel.init(title: "隐藏自己的守护", content: "开启后，隐藏已有守护，所有人可以再对你守护", isOn: attributes.myGuardHid)
        control.checkFaceStatus = false
        control.tapSwitchclosure = {[weak self] isOn in
            self?.tapHiddenGuardHandle(isOn: isOn)
        }
        return control
    }()
    
    fileprivate lazy var item4:ST_GeneralOfSwitchCell = {
        let control = ST_GeneralOfSwitchCell()
        let model0 = ST_GeneralOfSwitchCellModel()
        model0.infoKey = "隐身模式"
        control.cellModel = model0
        return control
    }()
    
    fileprivate lazy var item5:APNSOfSwitchCell = {
        let control = APNSOfSwitchCell()
        return control
    }()
    
    fileprivate lazy var item6:ST_OtherGeneralCell = {
        
        let control = ST_OtherGeneralCell()
        
        let model5 = ST_OtherGeneralCellModel()
        model5.infoKey = "黑名单"
        control.cellModel = model5
        
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(pushBlackList))
        control.addGestureRecognizer(tap)
        return control
    }()
    
    
    #if !targetEnvironment(simulator)
    fileprivate lazy var store:CNContactStore = {
        let s = CNContactStore()
        return s
    }()
    #endif
}

//    MARK: - Contact Store
extension ST_BTPrivacyViewController{
    
    fileprivate func contactAuthorizationError(){
        
        self.toast(text: "请允许访问通讯录")
        
        item0.model?.isOn = false
        
        item0.model = item0.model
        
        main_thread_execute(afterDelay: 1.5) {
            self.push_setting()
        }
    }
    
    fileprivate func push_setting(){
        
        PushTianSetting()
    }
    
    @objc func tapContactHandle(isOn:Bool){
        
        if !isOn{
            
            JVrequest(PH.uploadAddressBookApi,parameters: ["address_book_switch":"2"], success: { (json) in
                
                self.attributes.ignoreMyContacts = false
                
            }) { (code, err) in
                
                self.toast(text: err)
            }
            
        }else{
            
            print("获取通讯录")
            
            #if !targetEnvironment(simulator)
            let authorizationStatus = CNContactStore.authorizationStatus(for: CNEntityType.contacts)
            
            switch authorizationStatus {
            
            case .restricted,.denied:
                self.contactAuthorizationError()
                break
            case .authorized:
                self.fetchAllContacts()
                break
            default:
                //                    print("询问权限")
                self.requestAuthorizationStatus()
            }
            #endif
        }
    }
    
    
    
    fileprivate func requestAuthorizationStatus(){
        
        #if !targetEnvironment(simulator)
        store.requestAccess(for: CNEntityType.contacts) { (granted, error) in
            main_thread_execute {
                if granted {
                    self.fetchAllContacts()
                } else {
                    self.contactAuthorizationError()
                }
            }
        }
        #endif
    }
    
    
    fileprivate func fetchAllContacts(){
        #if !targetEnvironment(simulator)
        
        var results: [CNContact] = []
        
        let keysToFetch = [
            CNContactPhoneNumbersKey]
        
        var allContainers: [CNContainer] = []
        do {
            allContainers = try store.containers(matching: nil)
        } catch {
            return
        }
        
        for container in allContainers {
            
            let fetchPredicate = CNContact.predicateForContactsInContainer(withIdentifier: container.identifier)
            
            do {
                
                let containerResults = try store.unifiedContacts(matching: fetchPredicate, keysToFetch: keysToFetch as [CNKeyDescriptor])
                
                results.append(contentsOf: containerResults)
                
            } catch {
                return
            }
        }
        
        
        
        let numberResult = results.map { (contact) -> [String] in
            return contact.phoneNumbers.map { (number) -> String in
                return number.value.stringValue
            }
        }
        
        var numberString = numberResult.reduce("", { x, y in
            x + self.disposePhoneNumber(numberArray: y)
        })
        
        numberString = numberString.removingSuffix(",")
        
        
        JVrequest(PH.uploadAddressBookApi,parameters: ["address_book_switch":"1","phones":numberString], success: { (json) in
            
            self.attributes.ignoreMyContacts = true
            
        }) { (code, err) in
            
            self.toast(text: err)
            
        }
        
        
        
        #endif
    }
    
    fileprivate func disposePhoneNumber(numberArray:[String])->String{
        
        let str = numberArray.map { (str) -> String in
            
            var mStr = str
            
            mStr = mStr.removingPrefix("+86")
            
            mStr = mStr.removingWhitespaces()
            
            mStr = mStr.components(separatedBy: "-").joined()
            
            return mStr
            
        }.joined(separator: ",")
        
        print("小数组:",str)
        
        return str + ","
    }
    
    
    
}

extension ST_BTPrivacyViewController{
    
    @objc func tapOnlyMemberHandle(isOn:Bool){
        
        JVrequest(PH.setPrivacyValueApi,parameters: ["only_vip_talk": isOn ? "1":"2"], success: { (json) in
            
            self.attributes.allowMember = isOn
            
        }) { (code, err) in
            
            self.toast(text: err)
        }
        
    }
    
    @objc func tapOnlyTextTalkHandle(isOn:Bool){
        
        JVrequest(PH.setPrivacyValueApi,parameters: ["can_receive_source": isOn ? "2":"1"], success: { (json) in
            
            self.attributes.onlyAllowTextTalk = isOn
            
        }) { (code, err) in
            
            self.toast(text: err)
        }
    }
    
    
    @objc func tapAllowAutoSayHiHandle(isOn:Bool){
        
        JVrequest(PH.setAutoSendMsgApi,parameters: ["auto_send_msg": isOn ? "2":"1"], success: { (json) in
            
            self.attributes.allowAutoSayHi = isOn
            
        }) { (code, err) in
            
            self.toast(text: err)
        }
    }
    
    
    @objc func tapHiddenNobleHandle(isOn:Bool){
        
        JVrequest(PH.setPrivacyValueApi,parameters: ["nobility_close": isOn ? "2":"1"], success: { (json) in
            
            self.attributes.myNobilityHid = isOn
            
        }) { (code, err) in
            
            self.toast(text: err)
        }
    }
    
    
    @objc func tapHiddenGuardHandle(isOn:Bool){
        
        JVrequest(PH.setPrivacyValueApi,parameters: ["guard_close": isOn ? "2":"1"], success: { (json) in
            
            self.attributes.myGuardHid = isOn
            
        }) { (code, err) in
            
            self.toast(text: err)
        }
    }
    
    @objc func tapOnlyFaceHandle(isOn:Bool){
        
        JVrequest(PH.setPrivacyValueApi,parameters: ["only_face_talk": isOn ? "1":"2"], success: { (json) in
            
            self.attributes.allowTalkFaceDetected = isOn
            
        }) { (code, err) in
            
            self.toast(text: err)
        }
        
    }
    
    @objc func pushBlackList(){
        
        let vc = ST_BlacklistViewController()
        
        self.navigationController?.pushViewController(vc)
        
    }
}





//MARK: - Child View
fileprivate class PrivacySupplementBoxView:UIView{
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(info_label)
        info_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(25)
            make.top.equalToSuperview().offset(19)
            make.height.equalTo(22)
        }
        
        
        self.addSubview(infoSubLabel)
        infoSubLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(25)
            make.top.equalToSuperview().offset(44)
            make.height.equalTo(17)
        }
        
        self.addSubview(select_control)
        select_control.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-20)
        }
        
        let line = UIView()
        line.backgroundColor = UIColor.init(hex: 0xF2F4F7)
        self.addSubview(line)
        line.snp.makeConstraints { (make) in
            make.left.equalTo(info_label).offset(-5)
            make.height.equalTo(1)
            make.right.bottom.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate lazy var info_label:UILabel = {
        let control = UILabel.init()
        control.textColor = UIColor.init(hexString: "#333333")
        //        control.numberOfLines = 0
        control.textAlignment = .left
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        return control
    }()
    
    fileprivate lazy var infoSubLabel:UILabel = {
        let control = UILabel.init()
        control.textColor = UIColor.init(hexString: "#ACB4C0")
        //        control.numberOfLines = 0
        control.textAlignment = .left
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        return control
    }()
    
    fileprivate lazy var select_control:UISwitch = {
        let control = UISwitch()
        control.onTintColor = UIColor.init(hex: 0xFEC207)
        control.backgroundColor = UIColor.init(hex: 0xACB4C0)
        control.cornerRadius = 16
        control.addTarget(self, action: #selector(_switch_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    var model:PrivacySupplementBoxViewModel?{
        didSet{
            
            guard let m = model else {
                return
            }
            
            info_label.text = m.title
            infoSubLabel.text = m.content
            select_control.isOn = m.isOn
        }
    }
    
    
    var checkFaceStatus = true
    
    var tapSwitchclosure:((Bool)->())?
    
    @objc func _switch_handle(){
        
        if checkFaceStatus && select_control.isOn && FACE_AVATAE_STATE != 3{
            
            select_control.isOn = false
            
            self.parentViewController?.toast(text: "真人认证了才能开启此选项")
            
            return
        }
        
        
        tapSwitchclosure?(select_control.isOn)
    }
    
}

fileprivate struct PrivacySupplementBoxViewModel{
    
    var title:String
    var content:String
    var isOn:Bool
}

class APNSOfSwitchCell: UICollectionViewCell {
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(info_label)
        
        info_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(25)
            make.centerY.equalToSuperview()
        }
        contentView.addSubview(select_control)
        select_control.snp.makeConstraints { (make) in
            make.centerY.equalTo(info_label)
            make.right.equalToSuperview().offset(-20)
        }
        
        let line = UIView()
        line.backgroundColor = UIColor.init(hex: 0xF2F4F7)
        contentView.addSubview(line)
        line.snp.makeConstraints { (make) in
            make.left.equalTo(info_label).offset(-5)
            make.height.equalTo(1)
            make.right.bottom.equalToSuperview()
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var info_label:UILabel = {
        let control = UILabel.init()
        control.text = "通知显示消息详情"
        control.textColor = UIColor.init(hexString: "#333333")
        //        control.numberOfLines = 0
        control.textAlignment = .left
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        return control
    }()
    
    fileprivate lazy var select_control:UISwitch = {
        let control = UISwitch()
        control.onTintColor = UIColor.init(hex: 0xFEC207)
        control.backgroundColor = UIColor.init(hex: 0xACB4C0)
        control.cornerRadius = 16
        control.addTarget(self, action: #selector(_switch_handle), for: UIControl.Event.touchUpInside)
        
        if let setting = NIMSDK.shared().apnsManager.currentSetting(),setting.type == .detail {
            
            control.isOn = true
        }
        
        
        
        return control
    }()
    
    @objc func _switch_handle(){
        
        updateApnsSetting(showDetail: select_control.isOn)
        
    }
    
    fileprivate func updateApnsSetting(showDetail:Bool){
        
        let setting = NIMPushNotificationSetting.init()
        
        if showDetail{
            setting.type = .detail
        }else{
            setting.type = .noDetail
        }
        
        NIMSDK.shared().apnsManager.updateApnsSetting(setting) { (err) in
            
            guard let e = err else{
                return
            }
            self.parentViewController?.toast(text: e.localizedDescription)
            
        }
    }
    
    
    fileprivate func setOnLineModel(modelInt:Int){
        
        JVrequest(PH.setOnlineModeApi,parameters: ["online_mode":modelInt], success: { (json) in
            
            print("改变在线状态 成功:",modelInt)
            
            IS_INVISIBLE = modelInt == 2
            
            self.select_control.isOn = IS_INVISIBLE
            
        }) { (code, err) in
            
            self.select_control.isOn = IS_INVISIBLE
            
            self.parentViewController?.toast(text: err)
        }
        
        //
        
    }
}



func PushTianSetting() {
    
    if let settingsUrl =  UIApplication.openSettingsURLString.url{
        
        if #available(iOS 10.0, *) {
            
            UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
                print("Settings opened: \(success)") // Prints true
            })
        } else {
            
            UIApplication.shared.openURL(settingsUrl)
        }
    }
}
